<?php
/*
 * 	Manhali - Free Course Management System
 *	s_profiles.php
 *	2011-01-27 12:52
 * 	Author: El Haddioui Ismail <ismail.elhaddioui@gmail.com>
 * 	Copyright (C) 2009-2011  El Haddioui Ismail. All rights reserved
 * 	License : GNU/GPL v3

This file is part of Manhali

Manhali is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Manhali is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Manhali.  If not, see <http://www.gnu.org/licenses/>.

*/

defined("access_const") or die( 'Restricted access' );

function calcul_age ($birth) {
	$naissance = explode("/",$birth);
	$day = $naissance[0];
	$month = $naissance[1];
	$year = $naissance[2];
	$now = time();
	$thisday = date("d",$now);
	$thismonth = date("m",$now);
	$thisyear = date("Y",$now);
	if ($thismonth >= $month){
		$mois = $thismonth - $month;
		$annee = $thisyear - $year;
	} else {
		$mois = 12 + $thismonth - $month;
		$annee = $thisyear - $year - 1;
	}
	return $annee."-".$mois;
}

	if (!empty($_GET['s_profiles']) && ctype_digit($_GET['s_profiles']))
		$id_stu = intval($_GET['s_profiles']);
	else if (isset($id_user_session) && !empty($id_user_session) && $_SESSION['connect']["log"] == 2)
		$id_stu = $id_user_session;

	if (isset($id_stu) && !empty($id_stu) && $afficher_profil == 1){
		if (!empty($_GET['action']) && $_GET['action'] == "edit"){
			if (isset($_SESSION['connect']["log"]) && $_SESSION['connect']["log"] == 2 && $id_stu == $id_user_session){

				echo "<script language=\"javascript\" type=\"text/javascript\" src=\"styles/radio_div.js\"></script>";
				echo "<div id=\"titre\">".modifier_perso."</div><br />";
				goback_button();
				$err_comp = 0;

				$select_user = mysql_query("select * from `" . $tblprefix . "apprenants` where id_apprenant = $id_user_session;");
    		if (mysql_num_rows($select_user) == 1){
    			$user = mysql_fetch_row($select_user);
					
					$id_user = $user[0];
					$classe_user = $user[1];
					$nom_user = html_ent($user[2]);
					$identifiant_user = html_ent($user[3]);
					$mdp_user = $user[4];
					$email_user = html_ent($user[5]);
					$naissance_user = explode("/",$user[6]);
					$photo_profil = $user[8];
					$sexe_user = $user[9];
					
					// need classe
					$select_demande_classe = mysql_query("select demander_classe from `" . $tblprefix . "site_infos`;");
					if (mysql_num_rows($select_demande_classe) == 1) {
						$select_classes = mysql_query("select * from `" . $tblprefix . "classes`;");
						if (mysql_num_rows($select_classes) > 0 && mysql_result($select_demande_classe,0) == 1)
							$need_classe = 1;
						else $need_classe = 0;
					} else $need_classe = 0;
					
					//modifier classe
					$autoriser_modification_classe = mysql_query("select autoriser_modification_classe from `" . $tblprefix . "site_infos`;");
					if (mysql_num_rows($autoriser_modification_classe) == 1) {
						if (mysql_result($autoriser_modification_classe,0) == 1)
							$edit_classe = 1;
						else $edit_classe = 0;
					} else $edit_classe = 0;
											
					if (!empty($_POST['send']) && !empty($_POST['random'])){
					 if (!isset($_SESSION['random_key']) || $_SESSION['random_key'] != $_POST['random']){
					 	$_SESSION['random_key'] = $_POST['random'];
					 	
// update identifiant
						$login = trim($_POST['login']);
						if (!empty($login)){
							$login = special_chars($login);
							$login = escape_string($login);
							if ($login != $identifiant_user){
								$select_app_login = mysql_query("select id_apprenant from `" . $tblprefix . "apprenants` where identifiant_apprenant = '$login' and id_apprenant != $id_user;");
								$select_user_id = mysql_query("select id_user from `" . $tblprefix . "users` where identifiant_user = '$login';");
 								if (mysql_num_rows($select_app_login) == 0 && mysql_num_rows($select_user_id) == 0) {
 									$update_login = mysql_query("update `" . $tblprefix . "apprenants` set identifiant_apprenant = '$login' where id_apprenant = $id_user;");
 								}
 								else {
 									$err_comp = 1;
 									goback(login_existe,2,"error",0);
 								} 							
 							}
 						}

// update nom
						$name = trim($_POST['name']);
 						if (!empty($name)){
							$name = escape_string($name);
							if ($name != $nom_user){
 								$update_name = mysql_query("update `" . $tblprefix . "apprenants` set nom_apprenant = '$name' where id_apprenant = $id_user;");
 							}
 						}

// update sexe
						$sexe = trim($_POST['sexe']);
						if ($sexe != $sexe_user && ($sexe == "M" || $sexe == "F")){
							$danew_photo_profil = $photo_profil;
							if ($sexe == "M"){
								if ($photo_profil == "woman.jpg")
									$danew_photo_profil = "man.jpg";
 							}
 							else if ($sexe == "F"){
 								if ($photo_profil == "man.jpg")
 									$danew_photo_profil = "woman.jpg"; 
 							} 
 							$update_name = mysql_query("update `" . $tblprefix . "apprenants` set photo_apprenant = '$danew_photo_profil', sexe_apprenant = '$sexe' where id_apprenant = $id_user;");
 						}
 						
// update photo

if ($photo_profil == "man.jpg" || $photo_profil == "woman.jpg" || (isset($_POST['avatar']) && $_POST['avatar'] == "modifier")){
 	if(!empty($_FILES["uploaded_file"]) && $_FILES['uploaded_file']['error'] == 0) {
		$extensions = array("bmp","jpg","gif","png");
		$type_mime = array("bmp" => "image/bmp", "jpg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
		$type_mime2 = array("jpg" => "image/pjpeg", "png" => "image/x-png");
		$filename = $_FILES['uploaded_file']['name'];
  	$ext = substr($filename, strrpos($filename, '.') + 1);
  	$ext = strtolower($ext);
 		if (in_array($ext, $extensions) && ($_FILES["uploaded_file"]["type"] == $type_mime[$ext] || $_FILES["uploaded_file"]["type"] == $type_mime2[$ext])){
  		$new_file = fonc_rand(24).".".$ext;
  		while (file_exists("docs/".$new_file))
				$new_file = fonc_rand(24).".".$ext;
  		$destination = "docs/".$new_file;
			if ((@move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$destination))){
				$update_photo = mysql_query("update `" . $tblprefix . "apprenants` set photo_apprenant = '$new_file' where id_apprenant = $id_user;");
				if ($photo_profil != "man.jpg" && $photo_profil != "woman.jpg")
					@unlink("docs/".$photo_profil);
    	}
      else {
	  		$err_comp = 1;
        goback(erreur_upload,2,"error",0);
     	}
  	}
  	else {
  		$err_comp = 1;
			goback(erreur_upload_type,2,"error",0);
  	}
	}
} else if ($photo_profil != "man.jpg" && $photo_profil != "woman.jpg" && isset($_POST['avatar']) && $_POST['avatar'] == "supprimer"){
	if ($sexe == "M") $photo_remove = "man.jpg";
	else if ($sexe == "F") $photo_remove = "woman.jpg";
	else {
		if ($sexe_user == "M") $photo_remove = "man.jpg";
		else if ($sexe_user == "F") $photo_remove = "woman.jpg";
	}
 	$update_photo = mysql_query("update `" . $tblprefix . "apprenants` set photo_apprenant = '".$photo_remove."' where id_apprenant = $id_user;");
	@unlink("docs/".$photo_profil);
}
// update email
						$email = trim($_POST['email']);
 						if (!empty($email)){
							$email = escape_string($email);
							if ($email != $email_user){
								if (mail_valide($email)){
 									$update_email = mysql_query("update `" . $tblprefix . "apprenants` set email_apprenant = '$email' where id_apprenant = $id_user;");
 								}
 								else {
 									$err_comp = 1;
 									goback(format_mail_err,2,"error",0);
 								} 							
 							}
 						}

//update classe
				if ($need_classe == 1 && $edit_classe == 1 && ctype_digit($_POST['classe_app'])){
				 	if ($_POST['classe_app'] != $classe_user){
				 		$classe_app = $_POST['classe_app'];
				 		$update_classe = mysql_query("update `" . $tblprefix . "apprenants` set id_classe = $classe_app where id_apprenant = $id_user;");
				 	}
				}

//update naissance
				if ($_POST['jj'] != $naissance_user[0] || $_POST['mm'] != $naissance_user[1] || $_POST['yyyy'] != $naissance_user[2]){
					$jj = escape_string($_POST['jj']);
					$mm = escape_string($_POST['mm']);
					$yyyy = escape_string($_POST['yyyy']);
					if (ctype_digit($jj) && $jj >= 1 && $jj <= 31 && ctype_digit($mm) && $mm >= 1 && $mm <= 12 && ctype_digit($yyyy) && $yyyy >= (date("Y",time()) - 65) && $yyyy <= (date("Y",time()) - 5)){
					 	$naissance_app = $jj."/".$mm."/".$yyyy;
						$update_naissance = mysql_query("update `" . $tblprefix . "apprenants` set naissance_apprenant = '$naissance_app' where id_apprenant = $id_user;");
					}
					else {
						$err_comp = 1;
						goback(date_naissance_invalide,2,"error",0);
					}
				}

// update pass
						$new_password = trim($_POST['new_password']);
						$new_pass_conf = trim($_POST['new_pass_conf']);
						$old_password = trim($_POST['old_password']);
 						if (!empty($new_password) && !empty($new_pass_conf) && !empty($old_password)){
 							$new_password = escape_string($new_password);
	      			$new_pass_conf = escape_string($new_pass_conf);
	      			$old_password = escape_string($old_password);
 							if ($new_password == $new_pass_conf) {
 							 if (strlen($new_password) >= 5){
										$passpart1 = substr($mdp_user,0,32);
										$passpart2 = substr($mdp_user,32,4);
										$passpart3 = substr($mdp_user,36,4);
										if ($passpart1 == md5($passpart3.$old_password.$passpart2)){
											$rndm = fonc_rand(8);
	                    $rndm1 = substr($rndm,0,4);
	                    $rndm2 = substr($rndm,4,4);
	                    $crypt = md5($rndm2.$new_password.$rndm1);
	                    $mdp = $crypt.$rndm;
	                    $update_mdp = mysql_query("update `" . $tblprefix . "apprenants` set mdp_apprenant = '$mdp' where id_apprenant = $id_user;");
										}
 							 			else {
											$err_comp = 1;
											goback(old_mdp_invalide,2,"error",0);
										}
 							 }
 							 else {
 							 	$err_comp = 1;
 							 	goback(pass_court,2,"error",0);
 							 }
 							}
 							else {
 								$err_comp = 1;
 								goback(confirm_pass_err,2,"error",0);
 							}
 						}
						
						if ($err_comp == 0) redirection(infos_modifies."<br />".identifiant." : ".html_ent($login),"?s_profiles",10,"tips",0);
					 } else goback(err_data_saved,2,"error",0);
					}
					else {
					// ****** formulaire edit profile
    				echo "<form method=\"POST\" enctype=\"multipart/form-data\" action=\"\">";
    				echo "<p><b>" .nom_complet. " : </b><br /><input name=\"name\" type=\"text\" maxlength=\"30\" size=\"30\" value=\"".$nom_user."\"></p>";
	      		echo "<p><b>" .identifiant. " : </b><br /><input name=\"login\" type=\"text\" maxlength=\"30\" size=\"30\" value=\"".$identifiant_user."\"></p>";
	      		echo "<p><b>" .old_password. " : </b><br /><input name=\"old_password\" type=\"password\" maxlength=\"30\" size=\"30\" value=\"\"></p>";
	      		echo "<p><b>" .new_password. " : </b><br /><input name=\"new_password\" type=\"password\" maxlength=\"30\" size=\"30\" value=\"\"> " .carac5_min. "</p>";
	      		echo "<p><b>" .confirmpassword. " : </b><br /><input name=\"new_pass_conf\" type=\"password\" maxlength=\"30\" size=\"30\" value=\"\"></p>";
	      		echo "<p><b>" .email. " : </b><br /><input name=\"email\" type=\"text\" maxlength=\"50\" size=\"30\" value=\"".$email_user."\"></p>";

	      		if ($need_classe == 1){
	      			echo "<p><b>" .classe. " : </b><br /><select name=\"classe_app\"";
	      			if ($edit_classe == 0)
	      				echo " disabled=\"disabled\"";
	      			echo "><option value=\"0\"></option>";
    					while($classe = mysql_fetch_row($select_classes)){
    						$id_classe = $classe[0];
    						$nom_classe = $classe[1];
								echo "<option ";
								if ($classe_user==$id_classe) echo "selected=\"selected\" ";
								echo "value=\"".$id_classe."\">".$nom_classe."</option>";
							}
							echo "</select></p>";
						}
						echo "<p><b>" .date_naissance." : </b><br /><select name=\"jj\">";
						for ($day = 1; $day <= 31; $day++){
							echo "<option ";
							if (isset($naissance_user[0]) && $naissance_user[0]==$day) echo "selected=\"selected\" ";
							echo "value=\"".$day."\">".$day."</option>";
						}
						echo "</select> <select name=\"mm\">";
						foreach ($month_tab as $key_m => $month){
    					echo "<option ";
    					if (isset($naissance_user[1]) && $naissance_user[1]==$key_m) echo "selected=\"selected\" ";
    					echo "value=\"".$key_m."\">".$month."</option>";
    				}
						echo "</select> <select name=\"yyyy\">";
						for ($year = date("Y",time()) - 5; $year >= date("Y",time()) - 65; $year--){
							echo "<option ";
							if (isset($naissance_user[2]) && $naissance_user[2]==$year) echo "selected=\"selected\" ";
							echo "value=\"".$year."\">".$year."</option>";
						}
						echo "</select></p>";
						
						if ($sexe_user == "M") $chaine_m = " selected=\"selected\""; else $chaine_m = "";
						if ($sexe_user == "F") $chaine_f = " selected=\"selected\""; else $chaine_f = "";
						echo "<p><b>" .select_sex." : </b><br /><select name=\"sexe\">";
						echo "<option value=\"0\"></option>";
						echo "<option value=\"F\"".$chaine_f.">".female."</option>";
						echo "<option value=\"M\"".$chaine_m.">".male."</option>";
						echo "</select>";
						
	      		$upload_max_filesize = @ini_get('upload_max_filesize');
						echo "<p><b>" .photo_profil. " : </b><br />";
						echo "<img border=\"0\" src=\"docs/".$photo_profil."\" alt=\"".$nom_user."\" width=\"100\" height=\"100\" /><br /><br />";
						if ($photo_profil != "man.jpg" && $photo_profil != "woman.jpg"){
							echo "\n<b><input name=\"avatar\" type=\"radio\" value=\"modifier\" onclick=\"DisplayHide('avatar_div', 'edit')\"> " .modifier_photo. "</b>";
    					echo "<div style=\"display: none; margin-left: 20px;\" class=\"avatar_div\" id=\"edit\">";
						}
						echo "<input name=\"uploaded_file\" type=\"file\" />";
						echo "<input type=\"hidden\" name=\"random\" value=\"".fonc_rand(16)."\" />";
						echo "<br /><ul>";
						if (!empty($upload_max_filesize))
							echo "<li><b>".taille_max." ".$upload_max_filesize."</b></li>";
						echo "<li><b>".extentions_autorisees." : ".type_file1."</b></li>";
						echo "<li><b>".dimensions_recommandees."</b></li>";
						echo "</ul>";
						if ($photo_profil != "man.jpg" && $photo_profil != "woman.jpg"){
							echo "</div>";
							echo "\n<b><input name=\"avatar\" type=\"radio\" value=\"supprimer\" onclick=\"DisplayHide('avatar_div', 'delete')\"> " .supprimer_photo. "</b>";
    					echo "<div style=\"display: none; margin-left: 20px;\" class=\"avatar_div\" id=\"delete\">";
							echo "</div>";
						}	
						echo "</p>";
	    			echo "<p><input type=\"hidden\" name=\"send\" value=\"ok\"><input type=\"submit\" class=\"button\" value=\"" .btnsend. "\"></form>";
   				}
			 } else accueil();
			} else accueil();
		}
		else {
			
			// ********** afficher profil **********
			
			echo "<div id=\"titre\">".user_profile."</div>";
			goback_button();
			$select_stu = mysql_query("select * from `" . $tblprefix . "apprenants` where id_apprenant = $id_stu;");
    	if (mysql_num_rows($select_stu) == 1){
    			$user = mysql_fetch_row($select_stu);

					$id_classe = $user[1];
    		
					$nom_user = html_ent($user[2]);
					$identifiant_user = html_ent($user[3]);
					
					$email_user = html_ent($user[5]);
					$email_user = mail_antispam($email_user,0);
					
					$naissance_user = explode("/",$user[6]);
					
					$active_user = $user[7];
					$photo_profil = $user[8];
					
					if ($user[9] == "F") $sexe_user = female;
					else $sexe_user = male;
					
					$date_inscription = date("d/m/Y - H:i:s",$user[10]);
					
					if ($user[11] == 0)
						$last_connect = never;
					else
						$last_connect = date("d/m/Y - H:i:s",$user[11]);
						
					$online = $user[12];
					
					echo "<ul>";

					// ******** modifier compte & envoyer message
					if (isset($_SESSION['connect']["log"])){
						if ($id_stu == $id_user_session && $_SESSION['connect']["log"] == 2)
							echo "<a href=\"?s_profiles&action=edit\"><b>".modifier_perso."</b></a>";
						else {
							if ($_SESSION['connect']["log"] == 1 && isset($adminfolder)){
								if (substr($adminfolder,-1,1)=="/")
									$adminfolder = substr($adminfolder,0,strlen($adminfolder)-1);
								$link_edit = $adminfolder."/admin_home.php?inc=messages&do=new_msg&tolearner=".$id_stu;
							}
							else if ($_SESSION['connect']["log"] == 2)
								$link_edit = "?s_messages&do=new_msg&tolearner=".$id_stu;
							echo "<a href=\"".$link_edit."\"><b>".send_msg_to_user."</b></a>";
						}
					}
					
					// ******** infos
					if (!empty($photo_profil))
						echo "<p><img border=\"0\" src=\"docs/".$photo_profil."\" alt=\"".$nom_user."\" width=\"100\" height=\"100\" /></p>";
					
					echo "<p><h3>".$identifiant_user." (".$sexe_user.")</h3>";
					echo "<h3><font color=\"green\">" .learner. "</font></h3></p>";
					echo "<li><p><b>" .nom_complet. " : ".$nom_user."</b></p></li>";
					echo "<li><p><b>" .email. " : ".$email_user."</b></p></li>";
					
					$select_classe = mysql_query("select classe from `" . $tblprefix . "classes` where id_classe = $id_classe;");
    	  	if (mysql_num_rows($select_classe) == 1){
    				$classe = html_ent(mysql_result($select_classe,0));
						echo "<li><p><b>" .classe. " : ".$classe."</b></p></li>";
					}
					echo "<li><p><b>" .date_naissance. " : </b>";
					if (!empty($user[6])){
						echo "<b>".$naissance_user[0]." ".$month_tab[$naissance_user[1]]." ".$naissance_user[2]."</b>";
						$naissance = explode ("-",calcul_age($user[6]));
						echo " (".$naissance[0]." ".years." ".et." ".$naissance[1]." ".months.")";
					}
					echo "</p></li>";
					echo "<li><p><b>" .date_inscription. " : ".$date_inscription."</b></p></li>";
					echo "<li><p><b>" .last_connect. " : ".$last_connect."</b></p></li>";
					echo "<li><p><b>" .online. " : ";
					if ($online == 1)
						echo "<img border=\"0\" src=\"images/others/valide.png\" width=\"32\" height=\"32\" />";
					else
						echo "<img border=\"0\" src=\"images/others/delete.png\" width=\"32\" height=\"32\" />";
					echo "</p></li>";

					echo "<li><p><b>" .active. " : ";
					if ($active_user == 1)
						echo "<img border=\"0\" src=\"images/others/valide.png\" width=\"32\" height=\"32\" />";
					else
						echo "<img border=\"0\" src=\"images/others/delete.png\" width=\"32\" height=\"32\" />";
					echo "</p></li></ul>";
					
			} else accueil();
		}
	} else accueil();

?>